<template>
  <a-modal
    v-model:visible="visible"
    draggable
    width="40%"
    @ok="onSubmit"
    @cancel="handleChangeVisible"
  >
    <template #title> {{ title }}</template>
    <a-row>
      <a-col :flex="1">
        <a-form
          :model="formModel"
          :label-col-props="{ span: 3 }"
          :wrapper-col-props="{ span: 18 }"
          label-align="left"
        >
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item field="loginName" label="关键字">
                <a-input
                  v-model="formModel.loginName"
                  placeholder="请输入关键字"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-col>
      <a-col :flex="'86px'" style="text-align: right">
        <a-space direction="vertical" :size="18">
          <a-button type="primary" @click="search">
            <template #icon>
              <icon-search />
            </template>
            {{ $t('searchTable.form.search') }}
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <a-table
      v-model:selectedKeys="selectedKeys"
      row-key="id"
      :scroll="scroll"
      :loading="loading"
      :data="renderData.rows"
      :row-selection="rowSelection"
      :bordered="false"
      :pagination="{
        current: pagination.page,
        total: pagination.total,
        pageSize: pagination.rows,
        showTotal: true,
        showPageSize: true,
      }"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
    >
      <template #columns>
        <a-table-column title="用户名称" data-index="name" />
        <a-table-column title="用户登录名" data-index="loginName" />
      </template>
    </a-table>
  </a-modal>
</template>

<script lang="ts" setup>
  import { TableRowSelection } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { ref, reactive } from 'vue';
  import {
    selectPageUser,
    UserListParams,
    UserListRes,
    UserListVo,
    UserVo,
  } from '@/api/user';
  import { userVo } from '@/api/role';

  const generateFormModel = () => {
    return {
      gender: '',
      loginName: '',
      page: 1,
      personId: '',
      phone: '',
      positionId: '',
      roleId: '',
      rows: 20,
      tenantId: '',
      userId: '',
    };
  };
  const selectedKeys = ref<string[]>([]);
  const pagination = reactive({
    page: 1,
    rows: 20,
    total: 0,
  });
  const scroll = {
    y: 300,
  };
  const rowSelection = reactive<TableRowSelection>({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const { loading, setLoading } = useLoading();
  const renderData = ref<UserListRes>({
    rows: [] as Array<UserListVo>,
    total: 0,
  });
  const formModel = ref(generateFormModel());
  const visible = ref(false);
  const emit = defineEmits(['userSelection']);

  defineProps({
    title: {
      type: String,
      default: '选择用户',
    },
  });
  const fetchData = async (
    params: UserListParams // = { current: 1, pageSize: 20 }
  ) => {
    setLoading(true);
    try {
      const { data } = await selectPageUser(params);
      renderData.value = data;
      pagination.total = data.total;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const search = () => {
    fetchData(formModel.value as UserListParams);
  };

  const onPageChange = (current: number) => {
    pagination.page = current;
    search();
  };

  const onPageSizeChange = (pageSize: number) => {
    pagination.rows = pageSize;
    search();
  };

  function handleChangeVisible(list: Array<UserVo>) {
    visible.value = !visible.value;
    if (visible.value) {
      search();
      selectedKeys.value = list ? list.map((item) => item.id) : [];
    } else {
      selectedKeys.value = [];
    }
  }

  function onSubmit() {
    const arr: UserListVo[] = [];
    renderData.value.rows.forEach((item: UserListVo) => {
      selectedKeys.value.forEach((id: string) => {
        if (id === item.id) arr.push(item);
      });
    });
    emit('userSelection', { ids: selectedKeys.value, list: arr as userVo[] });
    selectedKeys.value = [];
  }

  defineExpose({ handleChangeVisible });
</script>

<script lang="ts">
  export default {
    name: 'SelectUser',
  };
</script>

<style scoped></style>
